﻿using System;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Web.DynamicData;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using NotAClue.Web;
using NotAClue.Web.DynamicData;
using NotAClue.ComponentModel.DataAnnotations;
using System.Web.Security;

namespace DD_Extensions
{
    public partial class ForeignKeyCascade_EditField : CascadingFieldTemplate //System.Web.DynamicData.FieldTemplateUserControl
    {
        private String _NotSet;
        private const string NOT_SET_STRING = "NotSet";

        #region Event
        // added page init to hookup the event handler Cascade
        protected void Page_Init(object sender, EventArgs e)
        {
            // add tool-tip
            this.SetupTip();

            // set field options
            this.SetFieldOptions();

            // add CSS from meta data
            this.ApplyCss();

            // add event handler if parent exists
            if (ParentControl != null)
                ParentControl.SelectionChanged += SelectedIndexChanged;
        }

        // raise event
        protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.SelectedValue = DropDownList1.SelectedItem.Value;
            RaiseSelectedIndexChanged(DropDownList1.SelectedItem.Value, DropDownList1.SelectedItem.Text);
        }

        // consume event
        protected void SelectedIndexChanged(object sender, SelectionChangedEventArgs e)
        {
            PopulateListControl(DropDownList1, e.Value);

            if (Mode == DataBoundControlMode.Insert)
                RaiseSelectedIndexChanged("", "");
            else
                RaiseSelectedIndexChanged(DropDownList1.Items[0].Value, DropDownList1.Items[0].Text);
        }
        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            _NotSet = String.Empty;

            var uIHint = Column.GetAttribute<UIHintAttribute>();
            if (uIHint != null && uIHint.ControlParameters.Count > 0)
            {
                if (uIHint.ControlParameters.ContainsKey(NOT_SET_STRING))
                    _NotSet = uIHint.ControlParameters[NOT_SET_STRING].ToString();
            }

            if (DropDownList1.Items.Count == 0)
            {
                if (Mode == DataBoundControlMode.Insert && Column.IsRequired)
                    DropDownList1.Items.Add(new ListItem("[Select one]", ""));
                else if (Mode == DataBoundControlMode.Insert || !Column.IsRequired)
                    DropDownList1.Items.Add(new ListItem("[Not Set]", ""));
            }

            SetUpValidator(RequiredFieldValidator1);
            SetUpValidator(DynamicValidator1);

            // set validators to use image as error indicator
            this.SetValidatorsToImage();

            SetupPopUp();

            // check to see if column is read only in insert mode
            Column.DisableFieldTemplate(Mode, DropDownList1);

            if (HasEvents)
                DropDownList1.AutoPostBack = true;
        }

        private void SetupPopUp()
        {
            var popup = MetadataAttributes.GetAttribute<PopupInsertAttribute>();
            if (popup != null)
            {
                // set pop-up page
                if (!String.IsNullOrEmpty(popup.PopupPage))
                    PopupButton1.PostBackUrl = ForeignKeyColumn.ParentTable.GetActionPath(popup.PopupPage);
                else
                    PopupButton1.PostBackUrl = ForeignKeyColumn.ParentTable.GetActionPath("PopupInsert");

                // set button legend
                if (!String.IsNullOrEmpty(popup.ButtonText))
                    PopupButton1.Text = popup.ButtonText;

                PopupButton1.Title = String.Format("InsertNew{0}", Table.Name);

                // set scroll bars
                PopupButton1.ScrollBars = popup.ScrollBars;
                PopupButton1.Visible = true;
                PopupButton1.WindowWidth = popup.WindowWidth;
                PopupButton1.WindowHeight = popup.WindowHeight;
            }
        }

        protected void PopupButton1_TextChanged(object sender, EventArgs e)
        {
            string foreignkey = PopupButton1.ReturnValues;
            //if no value just return don't do anything
            if (String.IsNullOrEmpty(PopupButton1.ReturnValues))
                return;

            // reset the DDL
            DropDownList1.Items.Clear();
            //PopulateListControl(DropDownList1);
            this.PopulateListControlFiltered(DropDownList1);

            if (!Column.IsRequired)
                DropDownList1.Items.Add(new ListItem("[Not Set]", ""));

            ListItem item = DropDownList1.Items.FindByValue(foreignkey);
            if (item != null)
                DropDownList1.SelectedValue = foreignkey;

            //DropDownList1.SetFocusHere();
        }

        protected override void OnDataBinding(EventArgs e)
        {
            base.OnDataBinding(e);

            if (ParentControl != null)
            {
                if (!String.IsNullOrEmpty(ParentControl.SelectedValue))
                    PopulateListControl(DropDownList1, ParentControl.SelectedValue);
            }
            else
                //PopulateListControl(DropDownList1);
                this.PopulateListControlFiltered(DropDownList1);

            string selectedValueString = GetSelectedValueString();
            ListItem item = DropDownList1.Items.FindByValue(selectedValueString);
            if (item != null)
            {
                DropDownList1.SelectedValue = selectedValueString;
                RaiseSelectedIndexChanged(DropDownList1.SelectedItem.Value, DropDownList1.SelectedItem.Text);
            }

            SelectedValue = DropDownList1.SelectedValue;
            if (Mode == DataBoundControlMode.Insert)
                SelectedValue = "";
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);

            if (DropDownList1.Items.Count == 1)
                DropDownList1.Items[0].Text = _NotSet;

            // configure auto post back
            if (HasEvents)
                DropDownList1.AutoPostBack = true;

            // set default values
            if (!IsPostBack && Mode == DataBoundControlMode.Insert)
            {
                var defaultValue = this.GetDefaultValue(Column);
                if (!String.IsNullOrEmpty(defaultValue))
                {
                    // try text and value for default
                    ListItem item = DropDownList1.Items.FindByValue(defaultValue);
                    if (item == null)
                        item = DropDownList1.Items.FindByText(defaultValue);

                    if (item != null)
                        DropDownList1.SelectedValue = item.Value;
                }
            }

            if (DropDownList1.Items.Count == 1)
                DropDownList1.Enabled = false;
            else
                DropDownList1.Enabled = true;
        }

        protected override void ExtractValues(IOrderedDictionary dictionary)
        {
            // If it's an empty string, change it to null
            string value = DropDownList1.SelectedValue;
            if (String.IsNullOrEmpty(value))
            {
                value = null;
            }

            ExtractForeignKey(dictionary, value);
        }

        public override Control DataControl
        {
            get { return DropDownList1; }
        }
    }
}
